﻿using System;
using GeoAPI.Geometries;

namespace NetTopologySuite.Algorithm
{
	public class RectangleLineIntersector
	{
		public RectangleLineIntersector(Envelope rectEnv)
		{
			this._rectEnv = rectEnv;
			this._diagUp0 = new Coordinate(rectEnv.MinX, rectEnv.MinY);
			this._diagUp1 = new Coordinate(rectEnv.MaxX, rectEnv.MaxY);
			this._diagDown0 = new Coordinate(rectEnv.MinX, rectEnv.MaxY);
			this._diagDown1 = new Coordinate(rectEnv.MaxX, rectEnv.MinY);
		}

		public bool Intersects(Coordinate p0, Coordinate p1)
		{
			Envelope other = new Envelope(p0, p1);
			if (!this._rectEnv.Intersects(other))
			{
				return false;
			}
			if (this._rectEnv.Intersects(p0))
			{
				return true;
			}
			if (this._rectEnv.Intersects(p1))
			{
				return true;
			}
			if (p0.CompareTo(p1) > 0)
			{
				Coordinate coordinate = p0;
				p0 = p1;
				p1 = coordinate;
			}
			if (p1.Y > p0.Y)
			{
				this._li.ComputeIntersection(p0, p1, this._diagDown0, this._diagDown1);
			}
			else
			{
				this._li.ComputeIntersection(p0, p1, this._diagUp0, this._diagUp1);
			}
			return this._li.HasIntersection;
		}

		private readonly LineIntersector _li = new RobustLineIntersector();

		private readonly Envelope _rectEnv;

		private readonly Coordinate _diagUp0;

		private readonly Coordinate _diagUp1;

		private readonly Coordinate _diagDown0;

		private readonly Coordinate _diagDown1;
	}
}
